package com.fsd.admin.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.fsd.admin.dao.B_templatelistDao;
import com.fsd.admin.dao.B_templatetypeDao;
import com.fsd.admin.model.A_Employee;
import com.fsd.admin.model.B_templatelist;
import com.fsd.admin.model.B_templatetype;
import com.fsd.admin.service.B_templatetypeService;
import com.fsd.core.bean.Tree;
import com.fsd.core.common.BusinessException;
import com.fsd.core.util.Config;
import com.fsd.core.util.ParametersUtil;
import com.google.gson.Gson;

@Repository("b_templatetypeServiceImpl")
public class B_templatetypeServiceImpl extends MainServiceImpl<B_templatetype, String> implements B_templatetypeService {
	private static final Logger log = Logger.getLogger(B_templatetypeServiceImpl.class);
	private String depict = "栏目专题";
	@Resource(name = "b_templatetypeDaoImpl")
	public void setBaseDao(B_templatetypeDao b_templatetypeDao) {
		super.setBaseDao(b_templatetypeDao);
	}

	@Resource(name = "b_templatetypeDaoImpl")
	private B_templatetypeDao typeDao;
	
	@Resource(name = "b_templatelistDaoImpl")
	private B_templatelistDao listDao;

	private String checkLeaf(String fid) {
		long num = typeDao.getCount("parentid = '" + fid + "'","deleted = '0'");
		if (num > 0)
			return "false";
		return "true";
	}

	private List<B_templatetype> queryObjectListById(String fid,
			String companyid) {
		return typeDao.queryByHql("from B_templatetype a where a.companyid = '"
				+ companyid + "' and a.parentid = '" + fid
				+ "' and a.deleted = '0' order by sort asc");
	}

	/**
	 * 加载分页数据
	 * 
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public ParametersUtil getObjectPageList(ParametersUtil param,A_Employee employee) throws Exception {
		Criteria c = typeDao.createCriteria();
		c.add(Restrictions.eq("deleted", "0"));
		c.add(Restrictions.eq("companyid", employee.getCompanyid()));
		c.addOrder(Order.asc("sort"));
		if (param.getJsonData() != null && !"".equals(param.getJsonData())) {
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if (objectMap.get("fid") != null
					&& !"".equals(objectMap.get("fid"))) {
				c.add(Restrictions.eq("parentid", objectMap.get("fid")));
			}
			if (objectMap.get("name") != null
					&& !"".equals(objectMap.get("name"))) {
				c.add(Restrictions.like("name", "%" + objectMap.get("name")
						+ "%"));
			}
		}
		return typeDao.findPager(param, c);
	}

	/**
	 * 异步加载对象树
	 * 
	 * @return
	 * @throws Exception
	 */
	public List<Tree> getAsyncObjectTree(String fid, A_Employee employee) throws Exception {
		List<Tree> treelist = new ArrayList<Tree>();
		List<B_templatetype> list = this.queryObjectListById(fid,
				employee.getCompanyid());
		Tree menu = null;
		for (B_templatetype obj : list) {
			menu = new Tree();
			menu.setId(obj.getId());
			menu.setText(obj.getName());
			menu.setLeaf(Boolean.valueOf(obj.getIsleaf()));
			treelist.add(menu);
		}
		return treelist;
	}

	/**
	 * 加载对象树
	 * 
	 * @return
	 * @throws Exception
	 */
	public List<Tree> getObjectTree(String fid, A_Employee employee) throws Exception {
		List<B_templatetype> list = typeDao
				.queryByHql("from B_templatetype a where a.companyid = '"
						+ employee.getCompanyid() + "' and a.deleted = '0' order by sort asc");
		List<Tree> treelist = this.getObjectTree(fid, list);
		return treelist;
	}

	private List<Tree> getObjectTree(String fid, List<B_templatetype> list)
			throws Exception {
		List<Tree> treelist = new ArrayList<Tree>();
		Tree node = null;
		for (B_templatetype obj : list) {
			if (obj.getParentid().equals(fid)) {
				node = new Tree();
				node.setId(obj.getId());
				node.setText(obj.getName());
				node.setLeaf(Boolean.valueOf(obj.getIsleaf()));
				if (!node.isLeaf()) {
					node.setChildren(this.getObjectTree(obj.getId(), list));
				}
				treelist.add(node);
			}
		}
		return treelist;
	}

	/**
	 * 保存对象（添加、修改）
	 * 
	 * @param obj
	 */
	public void saveObject(B_templatetype obj, A_Employee employee)
			throws Exception {
		if (obj.getId() != null && !"".equals(obj.getId())) {
			// 修改
			if (obj.getId().equals(obj.getParentid())){
    			throw new BusinessException(depict + "不得选择自己!");
        	}
			B_templatetype obj_old = typeDao.get(obj.getId());
			String fid = obj_old.getParentid();
			String name = obj_old.getName();
			obj_old.setParentid(obj.getParentid());
			obj_old.setParentname(obj.getParentname());
			obj_old.setName(obj.getName());
			obj_old.setCode(obj.getCode());
			obj_old.setSubjectid(obj.getSubjectid());
			obj_old.setAccessurl(obj.getTypecode()+"-"+obj.getCode()+".htm");
			obj_old.setSort(obj.getSort());
			obj_old.setRemark(obj.getRemark());
			obj_old.setUpdatedate(this.getData());// 设置修改日期
			obj_old.setUpdateemployeeid(employee.getId());// 设置修改用户id
			obj_old.setUpdateemployeename(employee.getRealname());// 设置修改用户姓名
			typeDao.update(obj_old);
			if (!fid.equals(obj.getParentid())){
				typeDao.executeHql("update B_templatetype t set t.isleaf = '" + this.checkLeaf(obj.getParentid()) + "' where t.id = '" + obj.getParentid() + "'");
				typeDao.executeHql("update B_templatetype t set t.isleaf = '" + this.checkLeaf(fid) + "' where t.id = '" + fid + "'");
			}
			if(!name.equals(obj_old.getName())){
				listDao.executeHql("update B_templatelist t set t.templatetypename = '" + obj_old.getName() + "' where templatetypeid = '" + obj_old.getId() + "'");
			}
		} else {
			// 添加
			obj.setId(this.getUUID());// 设置主键
			obj.setCompanyid(employee.getCompanyid());// 所属单位
			obj.setAdddate(this.getData());// 设置添加日期
			obj.setAddemployeeid(employee.getId());// 设置添加用户id
			obj.setAddemployeename(employee.getRealname());// 设置添加用户姓名
			obj.setAccessurl(obj.getTypecode()+"-"+obj.getCode()+".htm");
			obj.setIsleaf("true");
			obj.setDeleted("0");// 设置删除标志(0:正常 1：已删除)
			typeDao.save(obj);
			typeDao.executeHql("update B_templatetype t set t.isleaf = 'false' where t.id = '" + obj.getParentid() + "'");
			if(obj.getTypecode().equals("b_ztmb11") || obj.getTypecode().equals("b_ztmb12")){
				for(int i=1;i<=6;i++){
					B_templatelist objlist = new B_templatelist();
					objlist.setId(this.getUUID());
					objlist.setCompanyid(employee.getCompanyid());//所属单位
					objlist.setAdddate(this.getData());//设置添加日期
					objlist.setAddemployeeid(employee.getId());//设置添加用户id
					objlist.setAddemployeename(employee.getRealname());//设置添加用户姓名
					objlist.setDeleted("0");//设置删除标志(0:正常 1：已删除)
					objlist.setTemplatetypeid(obj.getId());
					objlist.setTemplatetypename(obj.getName());
					objlist.setTemplatetypecode(obj.getCode());
					objlist.setCode("csbm"+i);
					objlist.setSort(new Long(i));
					switch (i) {
						case 1:
							objlist.setName("顶部图片");
							objlist.setRemark("请填写图片地址");
							break;
						case 2:
							objlist.setName("幻灯图片");
							objlist.setRemark("请填写对应栏目ID");
							break;
						case 3:
							if(obj.getTypecode().equals("b_ztmb11")){
								objlist.setName("文章列表1");
								objlist.setRemark("请填写对应栏目ID");
							}else{
								objlist.setName("滚动文章");
								objlist.setRemark("请填写对应文章ID");
							}
							break;
						case 4:
							objlist.setName("文章列表2");
							objlist.setRemark("请填写对应栏目ID");
							break;
						case 5:
							objlist.setName("文章列表3");
							objlist.setRemark("请填写对应栏目ID");
							break;
						case 6:
							objlist.setName("滚动图片");
							objlist.setRemark("请填写对应栏目ID");
							break;
					}
					listDao.save(objlist);
					this.sysLogService.saveObject(Config.LOGTYPEBC,this.depict + objlist.getId() + objlist.getName(), employee, B_templatetypeServiceImpl.class);
				}
			}else{
				for(int i=1;i<=8;i++){
					B_templatelist objlist = new B_templatelist();
					objlist.setId(this.getUUID());
					objlist.setCompanyid(employee.getCompanyid());//所属单位
					objlist.setAdddate(this.getData());//设置添加日期
					objlist.setAddemployeeid(employee.getId());//设置添加用户id
					objlist.setAddemployeename(employee.getRealname());//设置添加用户姓名
					objlist.setDeleted("0");//设置删除标志(0:正常 1：已删除)
					objlist.setTemplatetypeid(obj.getId());
					objlist.setTemplatetypename(obj.getName());
					objlist.setTemplatetypecode(obj.getCode());
					objlist.setCode("csbm"+i);
					objlist.setSort(new Long(i));
					switch (i) {
						case 1:
							objlist.setName("顶部图片");
							objlist.setRemark("请填写图片地址");
							break;
						case 2:
							objlist.setName("幻灯图片");
							objlist.setRemark("请填写对应栏目ID");
							break;
						case 3:
							if(obj.getTypecode().equals("b_ztmb21")){
								objlist.setName("文章列表1");
								objlist.setRemark("请填写对应栏目ID");
							}else{
								objlist.setName("滚动文章");
								objlist.setRemark("请填写对应文章ID");
							}
							break;
						case 4:
							objlist.setName("文章列表2");
							objlist.setRemark("请填写对应栏目ID");
							break;
						case 5:
							objlist.setName("文章列表3");
							objlist.setRemark("请填写对应栏目ID");
							break;
						case 6:
							objlist.setName("文章列表4");
							objlist.setRemark("请填写对应栏目ID");
							break;
						case 7:
							objlist.setName("文章列表5");
							objlist.setRemark("请填写对应栏目ID");
							break;
						case 8:
							objlist.setName("滚动图片");
							objlist.setRemark("请填写对应栏目ID");
							break;
					}
					listDao.save(objlist);
					this.sysLogService.saveObject(Config.LOGTYPEBC,this.depict + objlist.getId() + objlist.getName(), employee, B_templatetypeServiceImpl.class);
				}
			}
		}
		this.sysLogService.saveObject(Config.LOGTYPEBC,this.depict + obj.getId() + obj.getName(), employee, B_templatetypeServiceImpl.class);
	}

	/**
	 * 删除对象
	 * 
	 * @param parameters
	 */
	@SuppressWarnings("unchecked")
	public void delObject(ParametersUtil parameters) throws Exception {
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String ids = "";
		String oid = "";
		for (String id : dir) {
			if (!ids.equals("")) {
				ids += ",";
			}
			ids += "'" + id + "'";
			oid = id;
		}
		typeDao
				.executeHql("update B_templatetype t set t.deleted = '1' where t.id in ("
						+ ids + ")");
		B_templatetype obj = typeDao.get(oid);
		if (obj != null) {
			typeDao.executeHql("update B_templatetype t set t.isleaf = '"
					+ this.checkLeaf(obj.getParentid()) + "' where t.id = '"
					+ obj.getParentid() + "'");
		}
	}

	/**
	 * 根据ID加载对象
	 * 
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	public B_templatetype getObjectById(ParametersUtil parameters)
			throws Exception {
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if (objectMap.get("id") == null && "".equals(objectMap.get("id"))) {
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		B_templatetype obj = typeDao.get(objectMap.get("id").toString());
		if (obj == null) {
			throw new BusinessException(depict + "数据不存在!");
		}
		return obj;
	}
}
